package de.uni_saarland.coli.doclists.index;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

public class MemoryDictionary implements IDictionary, Serializable {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 1632397959927013664L;

	private HashMap<String, Integer> forwardMap;
	private HashMap<Integer, String> backwardMap;

	private int lastId;

	public MemoryDictionary() {
		this.lastId = 0;
		this.forwardMap = new HashMap<String, Integer>();
		this.backwardMap = new HashMap<Integer, String>();
		this.addID("#DOCEND#");
	}

	@Override
	public int addID(String x) {
		if (!forwardMap.containsKey(x)) {
			this.forwardMap.put(x, this.lastId);
			this.backwardMap.put(this.lastId, x);
			this.lastId++;
		}

		return this.forwardMap.get(x);
	}

	@Override
	public int getID(String x) {
		if (forwardMap.containsKey(x))
			return this.forwardMap.get(x);
		return Integer.MIN_VALUE;

	}

	@Override
	public String getValue(int id) {
		if (this.backwardMap.containsKey(id))
			return this.backwardMap.get(id);
		return "";
	}
	
	@Override
	public boolean containsValue(String val) {
		return 0 != this.getID(val);
	}

	@Override
	public boolean containsKey(int id) {
		return this.backwardMap.containsKey(id);
	}


	@SuppressWarnings("unchecked")
	public void open(String path, String baseName) {
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(path + "/" + baseName + ".backwardMap");
			in = new ObjectInputStream(fis);
			this.backwardMap = (HashMap<Integer, String>) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		try {
			fis = new FileInputStream(path + "/" + baseName + ".forwardMap");
			in = new ObjectInputStream(fis);
			this.forwardMap = (HashMap<String, Integer>) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void save(String path, String baseName) {
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try {
			fos = new FileOutputStream(path + "/" + baseName + ".backwardMap");
			out = new ObjectOutputStream(fos);
			out.writeObject(this.backwardMap);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		try {
			fos = new FileOutputStream(path + "/" + baseName + ".forwardMap");
			out = new ObjectOutputStream(fos);
			out.writeObject(this.forwardMap);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
